<template>
  <div class="daily-report-list">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchParams" class="search-form">
      <!-- 日期范围选择器 -->
      <el-form-item label="报工日期:">
        <el-date-picker
          v-model="searchParams.workDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <!-- 管理员可见的报工人搜索 -->
      <el-form-item label="报工人:" v-if="isAdmin">
        <el-input v-model="searchParams.workerName" placeholder="请输入报工人" />
      </el-form-item>
      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="resetSearch">重置</el-button>
        <el-button type="success" icon="el-icon-plus" @click="onAddReport">新增报工</el-button>
      </el-form-item>
    </el-form>

    <!-- 日报列表表格 -->
    <el-table
      :data="reportList"
      border
      stripe
      style="width: 100%;"
      class="table-striped"
      v-loading="loading"
      :default-sort="{ prop: 'workDate', order: 'descending' }"
    >
      <!-- 报工日期 -->
      <el-table-column prop="workDate" label="报工日期" width="150" sortable />
      <!-- 报工人 -->
      <el-table-column prop="workerName" label="报工人" width="120" />
      <!-- 工作时长 -->
      <el-table-column prop="workHours" label="工作时长 (h)" width="120" />
      <!-- 提交时间 -->
      <el-table-column prop="createdAt" label="提交时间" width="200" sortable />
      <!-- 更新时间 -->
      <el-table-column prop="updatedAt" label="更新时间" width="200" sortable />
      <!-- 状态列，使用字典映射展示 -->
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusDescription(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" style="width: 100%">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleViewDetails(scope.row)">详情</el-button>
          <el-button
            size="mini"
            type="warning"
            @click="handleEditReport(scope.row)"
            v-if="canEditOrDelete(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDeleteReport(scope.row)"
            v-if="canEditOrDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next"
      :total="pagination.total"
      class="pagination"
    />
  </div>
</template>

<script>
import service from "@/utils/request";

export default {
  name: "DailyReportList",
  data() {
    return {
      searchParams: {
        workDateRange: [], // 查询日期范围
        workerName: "" // 查询的报工人
      },
      reportList: [], // 日报数据列表
      pagination: {
        currentPage: 1, // 当前页码
        pageSize: 10, // 每页显示条数
        total: 0 // 数据总数
      },
      loading: false, // 加载状态
      // 状态字典
      statusMap: {
        0: "草稿",
        1: "已提交"
      }
    };
  },
  computed: {
    /**
     * 判断是否为管理员
     */
    isAdmin() {
      return this.$store.state.user.roles?.includes("admin");
    },
    /**
     * 获取当前用户名
     */
    currentUserName() {
      return this.$store.state.user?.name || "";
    }
  },
  methods: {
    /**
     * 获取状态描述
     * @param {Number} statusCode 状态码
     * @returns {String} 状态描述
     */
    getStatusDescription(statusCode) {
      return this.statusMap[statusCode] || "未知状态";
    },

    /**
     * 根据状态获取 Tag 样式
     * @param {Number} statusCode 状态码
     * @returns {String} Tag 类型
     */
    getStatusType(statusCode) {
      switch (statusCode) {
        case 0:
          return "info"; // 草稿显示为蓝色
        case 1:
          return "success"; // 已提交显示为绿色
        default:
          return "warning"; // 未知状态显示为橙色
      }
    },

    /**
     * 获取日报列表
     */
    async getReportList() {
      this.loading = true;
      try {
        const params = {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          startDate: this.searchParams.workDateRange[0]
            ? this.searchParams.workDateRange[0].toISOString().split("T")[0]
            : "",
          endDate: this.searchParams.workDateRange[1]
            ? this.searchParams.workDateRange[1].toISOString().split("T")[0]
            : ""
        };

        if (this.isAdmin) {
          // params.status = 1; // 管理员查看已提交的
          if (this.searchParams.workerName) {
            params.workerName = this.searchParams.workerName;
          }
        } else {
          params.workerName = this.currentUserName;
        }

        const res = await service.get("/reports/list", { params });
        if (res.code === 200) {
          this.reportList = res.data.records || [];
          this.pagination.total = res.data.total || 0;
        } else {
          this.$message.error(res.message || "获取日报列表失败");
        }
      } catch (err) {
        this.$message.error("获取日报列表失败");
      } finally {
        this.loading = false;
      }
    },

    /**
     * 查询按钮操作
     */
    onSearch() {
      this.pagination.currentPage = 1;
      this.getReportList();
    },

    /**
     * 重置查询条件
     */
    resetSearch() {
      this.searchParams = { workDateRange: [], workerName: "" };
      this.onSearch();
    },

    /**
     * 跳转到新增日报页面
     */
    onAddReport() {
      this.$router.push("/report/new");
    },

    /**
     * 查看详情
     */
    handleViewDetails(row) {
      this.$router.push(`/report/detail/${row.id}`);
    },

    /**
     * 编辑日报
     */
    handleEditReport(row) {
      this.$router.push(`/report/edit/${row.id}`);
    },

    /**
     * 删除日报
     */
    async handleDeleteReport(row) {
      try {
        await this.$confirm("确定要删除这条日报吗？", "提示", {
          type: "warning"
        });
        const res = await service.delete(`/reports/delete/${row.id}`);
        if (res.code === 200) {
          this.$message.success("删除成功");
          this.onSearch();
        } else {
          this.$message.error(res.message || "删除失败");
        }
      } catch (e) {
        if (e !== "cancel") {
          this.$message.error("删除失败");
        }
      }
    },

    /**
     * 分页大小改变
     */
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.getReportList();
    },

    /**
     * 分页页码改变
     */
    handleCurrentChange(page) {
      this.pagination.currentPage = page;
      this.getReportList();
    },

    /**
     * 判断是否能编辑/删除
     */
    canEditOrDelete(row) {
      return this.isAdmin || row.workerName === this.currentUserName;
    }
  },
  mounted() {
    this.getReportList();
  }
};
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.daily-report-list {
  padding: 10px;
}

/* 斑马纹表格样式 */
.table-striped .el-table__row--striped:nth-child(odd) {
  background-color: #f9f9f9;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
